package com.ueboot.weishop.admin.batch;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.repository.JobRepository;

public class JobRunUtil {
	private static Logger logger = LoggerFactory.getLogger(JobRunUtil.class);

	public static void runJob(Job job, JobParameters params, JobRepository jobRepository, JobLauncher jobLauncher) {
		String jobName = job.getName();
		try {
			JobExecution jobExecution = jobRepository.getLastJobExecution(jobName, params);
			if (jobExecution != null) {
				String exitCode = jobExecution.getExitStatus().getExitCode();
				if ("COMPLETED".equals(exitCode)) {
					logger.info("*******current job is COMPLETED jobName:{},jobParams:{}", new Object[]{jobName, params.toString()});
				}else if ("FAILED".equals(exitCode)) {
					logger.info("*******current job is FAILED jobName:{},jobParams:{}", new Object[]{jobName, params.toString()});
				}
			} else {
				//异步操作，放入队列，等待调度
				jobLauncher.run(job, params);
				logger.info("{} is running params:{}", new Object[]{jobName, params.toString()});
			}
		} catch (Exception e) {
			logger.error(jobName + " error", e);
		}
	}
}
